﻿using System;
using System.Linq;
using System.ServiceModel.Syndication;
using System.Web.Mvc;
using WeBlog.ActionResults;
using WeBlog.Interfaces;
using WeBlog.Repositories;
using WeBlog.Services;

namespace WeBlog.Models
{
    public class SyndicationManager
    {        
        private readonly IUnitOfWork _unitOfWork;
        private SiteConfiguration _configuration;

        public SyndicationManager( IUnitOfWork unitOfWork )
        {
            _unitOfWork = unitOfWork;
            _configuration = SiteManager.CurrentConfiguration;
        }

        public ActionResult GetFeedResult(int? page = 1 )
        {
            var repository = new PostRepository(_unitOfWork);            
            var feed = new SyndicationFeed( _configuration.Name,
                                            _configuration.Description,
                                            new Uri(SiteManager.GetBaseUrl()));

            int pageIndex = (page ?? 1) - 1;
            feed.Items = repository.PublishedPosts()
				.OrderByDescending(p => p.PublishDate)
                .Skip(pageIndex * _configuration.PostsPerPage)
                .Take(_configuration.PostsPerPage)
                .ToList()
                .Select(x => new SyndicationItem(
                                 x.Title,
                                 x.Content,
                                 x.GetPermalink(),
                                 x.PostId.ToString(),
                                 x.PublishDate ?? DateTime.Now)
                );

            if (_configuration.FeedFormat.Equals("Atom", StringComparison.InvariantCultureIgnoreCase))
                return new AtomActionResult() {Feed = feed};

            return new RssActionResult() {Feed = feed};
        }
    }
}